<template>
  <div>
    <div class="table_ground">
      <div class="module_name">用户管理</div>
      <div class="input_button">
        <div class="input_box">
          <el-input placeholder="请输入用户名查询" size="small"  v-model="search.userName" class="input_left">
            <template #suffix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <el-button type="success" size="small" style="border-radius: 1px;width: 100px;text-align: center" @click="load">查询</el-button>
          <el-popconfirm title="确定删除这些数据吗？" @confirm="delBatch()">
            <template #reference>
              <el-button slot="reference" size="small" type="danger" style="margin-left: 10px;border-radius: 1px;width: 100px;text-align: center">批量删除</el-button>
            </template>
          </el-popconfirm>
        </div>

        <div class="button_box">
          <el-button type="success" size="small" style="border-radius: 1px;width: 100px;text-align: center; margin-right: 10px" @click="add">新增</el-button>
        </div>
        <el-upload :action="'http://localhost:8899/user/upload?token=' + token" style="display: inline-block" :on-success="impSuccessUpload" :show-file-list="false">
          <el-button style="margin-right: 10px" size="small" type="primary" >导入excel</el-button>
        </el-upload>
        <el-button size="small" type="warning" @click="exp" >导出excel</el-button>
      </div>
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          :fit="true"
          stripe
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
      >

<!--        <el-table :data="tableData" border style="width: 100%" :fit="true" stripe :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center' }" :row-key="getRowKeys"  @selection-change="handleSelectionChange">-->

<!--      <el-table-->
<!--          :data="tableData"-->
<!--          border-->
<!--          style="width: 100%"-->
<!--          :fit="true"-->
<!--          stripe-->
<!--          :cell-style="{ textAlign: 'center' }"-->
<!--          :header-cell-style="{ textAlign: 'center' }"-->
<!--          :row-key="getRowKeys"-->
<!--          @selection-change="handleSelectionChange"-->
<!--      >-->

        <el-table-column type="selection" width="55" />
<!--        <el-table-column label="Date" width="120">-->
<!--          <template #default="scope">{{ scope.row.date }}</template>-->
<!--        </el-table-column>-->


        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column label="头像">
          <template v-slot="scope">
            <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" style="width: 50px; height: 50px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="gender" label="性别"></el-table-column>
        <el-table-column prop="gradeName" label="所属班级"></el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <el-button @click="handleClick(row)" type="text" size="small">查看</el-button>
            <el-button type="text" size="small" @click="edit(row)">编辑</el-button>
            <!--            <el-button type="text" size="small" @click="edit('123')">编辑2</el-button>-->
            <!--            <el-button type="text" size="small">编辑</el-button>-->
            <el-popconfirm title="确定删除吗？"  @confirm="del(row.id)">
              <template #reference>
                <el-button type="text" size="small">删除</el-button>
              </template>
            </el-popconfirm>

            <el-popconfirm title="修改之后，该管理员所有相关信息都会删除，确定修改吗？"  @confirm="changeRole(row)">
              <template #reference>
                <el-button type="text" size="small">修改权限</el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="text-align: right; margin-top: 20px">
        <!--        <el-pagination-->
        <!--            v-model:current-page="pageNum"-->
        <!--            :page-size="5"-->
        <!--            :size="size"-->
        <!--            :disabled="disabled"-->
        <!--            :background="background"-->
        <!--            layout="total, prev, pager, next"-->
        <!--            :total="1000"-->
        <!--            @size-change="handleSizeChange"-->
        <!--            @current-change="handleCurrentChange"-->
        <!--        />-->

        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="5"
            layout="total, prev, pager, next"
            :total="total"
        />
      </div>
    </div>

    <!--    <div class="block" style="text-align: right; margin-top: 20px">-->

    <!--    </div>-->

    <!--    <template v-slot="scope">-->
    <!--      <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" style="width: 50px; height: 50px; border-radius: 50%"></el-image>-->
    <!--    </template>-->


    <el-dialog title="请填写信息" v-model="dialogVisible" width="40%">
      <el-form :model="form" label-position="right" label-width="100px" style="padding-right: 40px">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8899/files/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <!--          <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />-->
          <img v-if="form.avatar" :src="form.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <el-form-item label="用户名">
          <el-input size="small" v-model="form.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group size="small" v-model="form.gender">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input size="small" v-model="form.age" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input size="small" v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="所属班级">
          <el-select size="small" style="width: 100%" v-model="form.gradeId" @change="handleGradeChange">
            <el-option
                v-for="item in gradeData"
                :key="item.id"
                :value="item.id"
                :label="item.gradeName"
            ></el-option>
          </el-select>


        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="save">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="请填写信息" v-model="dialogRole" width="40%">
      <el-form :model="form" label-position="right" label-width="100px" style="padding-right: 40px">
        <el-form-item label="权限修改为">
          <el-radio-group size="small" v-model="form.role">
            <el-radio lable="1" >管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="change">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<!--<script setup>-->
<script lang="ts" setup>
import { ref } from 'vue'
// import { ref, reactive } from 'vue';
import type { ComponentSize } from 'element-plus'
import {Plus, Search} from "@element-plus/icons-vue";
import request from '@/utils/request';
import {ElNotification} from "element-plus";
import { onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
// import {reactive} from "vue/dist/vue";
import {reactive} from "vue";

const form = ref<{ [key: string]: any }>({
});

const token = localStorage.getItem("token");

const impSuccessUpload = () => {
  ElNotification.success('导入成功');
  load();
}

const dialogVisible = ref(false);  // 控制弹框的显示状态

const input = ref<string>('');
const pageNum = ref<number>(1);
let total = ref<number>(0);
const search = ref<{ [key: string]: any }>({});
let tableData = ref<any[]>([]);

const gradeData = ref<any[]>([]);

const dialogRole = ref<boolean>(false);

const selectionData = ref<any[]>([]);
// const selectionData = ref([])

onMounted(() => {
  load();
  loadGrade();
});

const user = reactive(JSON.parse(localStorage.getItem('user') || '{}'));

const load = () => {

  console.log('搜索结果', search.value.userName);

  //Get 方法获取所有数据
  // request.get("user/alldata").then((res: any) => {
  //
  //   if (res.code === '0') {
  //     // @ts-ignore
  //      tableData.value = res.data;
  //     // this.tableData = res.data
  //   } else {
  //     // @ts-ignore
  //     // this.$notify.error(res.msg);
  //
  //     ElNotification.error({
  //       title: '错误啦，请在 IDEA 搜索：error_01 ',
  //       message: res.msg
  //     });
  //   }
  // });

  request.post("/user/page?pageNum=" + pageNum.value, search.value).then((res: any) => {

    if (res.code === '0') {
      tableData.value = res.data.list;
      total.value = res.data.total;
      // tableData.value[0].id = '777'
    } else {
      // this.$notify.error(res.msg);
      ElNotification.error({
        title: '错误啦，请在 IDEA 搜索：user_error_01 ',
        message: res.msg
      });
    }

    console.log('load() --- ', res);
  });

};

const add = (): void => {
  form.value = {
    role: 2//默认用户
  };
  dialogVisible.value = true;
};

// @ts-ignore
const del = async (id: number): Promise<void> => {
  //方法一
  // try {
  //   const res: any = await request.delete(`/user/${id}`);
  //   if (res.code === '0') {
  //     ElNotification.success('删除成功');
  //     load();
  //   } else {
  //     ElNotification.error(res.msg);
  //   }
  // } catch (error) {
  //   ElNotification.error('删除失败，请重试');
  // }

  //方法二
  request.delete("/user/" + id).then((res: any) => {
    if (res.code === '0') {
      ElNotification.success('删除成功');
      load();
    } else {
      ElNotification.error(res.msg);
    }
  });
};

const edit = (row: { [key: string]: any }) => {
  dialogVisible.value = true;
  //form.value = row;
  form.value = JSON.parse(JSON.stringify(row)); //用了上面的会更改到表格数据，这个只会更改弹窗数据
  console.log('row 是否有值:', row);  // 如果没有值，检查数据渲染问题
};

const changeRole = (row: { [key: string]: any }) => {
  form.value = JSON.parse(JSON.stringify(row));
  dialogRole.value = true;
}
const change = () => {
  request.post("/user/changeRole",form.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

    if (res.code === '0'){ //如果接口调用成功，则把模态框关闭，重新加载一下数据库的数据

      ElNotification.success('角色修改成功');
      dialogRole.value = false;
      load();
    } else {
      ElNotification.error(res.msg);// 如果不成功，返回报错信息
    }
  })
};

// @ts-ignore
const save = async (): Promise<void> => {

  if (!form.value.id){ //如果没有id 走新增接口
    form.value.gradeName = 'test'
    request.post("/user",form.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

      if (res.code === '0'){ //如果接口调用成功，则把模态框关闭，重新加载一下数据库的数据

        ElNotification.success('新增成功');
        dialogVisible.value = false;
        load();
      } else {
        ElNotification.error(res.msg);// 如果不成功，返回报错信息
      }
    })
    console.log('--- 新增', form.value);
  }
  else {
    request.post("/user/edit",form.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

      if (res.code === '0'){
        ElNotification.success('修改成功');
        dialogVisible.value = false;
        load();
      } else {
        ElNotification.error(res.msg);
      }
    })
    console.log('--- 修改');
  }
};

const currentPage1 = ref(5)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)

const handleClick = (row: { [key: string]: any }) => {
  console.log(row)
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
// const handleCurrentChange = (val: number) => {
//   console.log(`current page: ${val}`)
// }
// 处理分页变化
const handleCurrentChange = (newPage: number) => {
  pageNum.value = newPage;
  console.log('当前页码:', newPage);
  load(); // 重新加载数据
};

const loadGrade = () => {

  request.get('/grade/alldata').then((res: any) => {

    if (res.code === '0') {
      gradeData.value = res.data;
      console.log('gradeData.value --- ', gradeData.value);
    } else {
      // this.$notify.error(res.msg);
      ElNotification.error({
        title: '错误啦，请在 IDEA 搜索：user_error_01 ',
        message: res.msg
      });
    }

    console.log('loadGrade() --- ', res);
  });

};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  form.value.avatar = response.data;
  // form.value.imageUrl = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

function handleGradeChange(value) {
  const selected = gradeData.value.find(item => item.id === value)
  if (selected) {
    form.value.gradeName = selected.gradeName
  }
}

const exp = () => {
  location.href = 'http://localhost:8899/user/export?token=' + token
}

const delBatch = () => {
  // ElNotification.success(selectionData.value)
  console.log('val------', selectionData.value);


  // 方式2写法// 调接口把选中的数据集合传给后端，后端拿到之后循环获取每个数据的Id，根据id执行删除操作

    // request.post("user/delBatch",this.selectionData).then(res => {
    //   if (res.code === '0'){
    //     this.$notify.success("批量删除成功");
    //     this.load();
    //   } else {
    //     this.$notify.error(res.msg);
    //   }
    // })

  request.post("user/delBatch",selectionData.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

    if (res.code === '0'){
      ElNotification.success('批量删除成功');
      load();
    } else {
      ElNotification.error(res.msg);
    }
  })
}


const getRowKeys = (row) => {//方式1写法
  return row.id
}
// const getRowKeys = (row: any) => row.id;// 方式2写法

const handleSelectionChange = (val) => {
  selectionData.value = val
}

</script>
